import type { StudentWordShorthandStudyParams } from '@/api/types/student'
import { handleApiError } from '@/api'
import { studentApi } from '@/api/modules/student'
import { useCurrentStudentInfoStore } from '@/stores/modules/useCurrentStudentInfoStore'
import { useUnitStudyWordsStore } from '@/stores/modules/useUnitStudyWordsStore'
import { calculateDurationInSeconds } from '@/utils/date'
import { formatDate } from '@/utils/format'

const studentInfoStore = useCurrentStudentInfoStore()

// 学习流程公式参考 learningStateMachine.md
// 如果将来需要修改学习流程规则，只需要修改 getNextState 函数中的逻辑，而不需要修改各个页面的代码。
// 如果需要添加新的学习状态，只需要：
// 在 LearningState 枚举中添加新状态
// 在 getNextState 函数中添加相应的转换逻辑
// 在 navigateToState 函数中添加相应的导航逻辑

// 学习状态定义
export enum LearningState {
  /** 单词识记 */
  WORD_MEMORY = 'wordMemory',
  /** 剪纸条 */
  CUTTING = 'cutting',
  /** 混合组检查 */
  MIXED_GROUP = 'mixedGroup',
  /** 6n组混合检查 */
  MIXED_GROUP_6N = 'mixedGroup6n',
  /** 混合全部检查 */
  MIXED_GROUP_ALL = 'mixedGroupAll',
  /** 学后检查 */
  AFTER_CHECK = 'afterCheck',
  /** 学习完成 */
  COMPLETED = 'completed',
}

// 获取下一个状态和相关信息
export function getNextState(currentState: LearningState, currentGroupIndex: number, totalGroups: number): {
  state: LearningState
  groupIndex?: number
  mixedGroups?: number[]
} {
  //   const unitStudyWordsStore = useUnitStudyWordsStore()

  console.log('currentState', currentState)
  console.log('currentGroupIndex', currentGroupIndex)
  console.log('totalGroups', totalGroups)

  // 单词识记 -> 剪纸条
  if (currentState === LearningState.WORD_MEMORY) {
    return { state: LearningState.CUTTING }
  }

  // 剪纸条后的决策逻辑
  if (currentState === LearningState.CUTTING) {
    // 只有1组的情况
    if (totalGroups === 1) {
      return { state: LearningState.AFTER_CHECK }
    }

    // 判断当前组的形式 (1-based index)
    const groupNumber = currentGroupIndex + 1
    const remainder = groupNumber % 3

    // 3N+1形式
    if (remainder === 1) {
      // 是否是最后一组
      if (currentGroupIndex === totalGroups - 1) {
        // 如果总组数 > 3，进入混合全部检查
        return totalGroups > 3
          ? { state: LearningState.MIXED_GROUP_ALL }
          : { state: LearningState.AFTER_CHECK }
      }
      else {
        // 不是最后一组，进入下一组单词识记
        return {
          state: LearningState.WORD_MEMORY,
          groupIndex: currentGroupIndex + 1,
        }
      }
    }

    // 3N+2形式
    if (remainder === 2) {
      return {
        state: LearningState.MIXED_GROUP,
        mixedGroups: [currentGroupIndex - 1, currentGroupIndex],
      }
    }

    // 3N形式
    if (remainder === 0) {
      // 如果小于等于3 的时候 直接进入混合全部
      if (totalGroups <= 3) {
        return {
          state: LearningState.MIXED_GROUP_ALL,
        }
      }

      return {
        state: LearningState.MIXED_GROUP,
        mixedGroups: [currentGroupIndex - 2, currentGroupIndex - 1, currentGroupIndex],
      }
    }
  }

  // 混合组检查后的决策逻辑
  if (currentState === LearningState.MIXED_GROUP) {
    console.log('currentGroupIndex', currentGroupIndex)
    // 判断当前组的形式 (1-based index)
    const groupNumber = currentGroupIndex + 1
    const remainder = groupNumber % 6

    // 如果是6n ， 并且不是最后一组
    if (remainder === 0 && currentGroupIndex !== totalGroups - 1) {
      // 检查1-6组，使用新的状态MIXED_GROUP_6N
      return {
        state: LearningState.MIXED_GROUP_6N,
        mixedGroups: [currentGroupIndex - 5, currentGroupIndex - 4, currentGroupIndex - 3, currentGroupIndex - 2, currentGroupIndex - 1, currentGroupIndex],
      }
    }

    // 如果已完成所有组
    if (currentGroupIndex === totalGroups - 1) {
      // 如果总组数 > 3，进入混合全部检查
      return totalGroups > 3
        ? { state: LearningState.MIXED_GROUP_ALL }
        : { state: LearningState.AFTER_CHECK }
    }

    // 否则进入下一组单词识记
    return {
      state: LearningState.WORD_MEMORY,
      groupIndex: currentGroupIndex + 1,
    }
  }

  // 处理6n组混合检查后的逻辑
  if (currentState === LearningState.MIXED_GROUP_6N) {
    // 6n组混合检查完成后，进入下一组单词识记
    return {
      state: LearningState.WORD_MEMORY,
      groupIndex: currentGroupIndex + 1,
    }
  }

  // 混合全部检查后进入学后检查
  if (currentState === LearningState.MIXED_GROUP_ALL) {
    return { state: LearningState.AFTER_CHECK }
  }

  // 学后检查后完成学习
  if (currentState === LearningState.AFTER_CHECK) {
    return { state: LearningState.COMPLETED }
  }

  // 默认保持当前状态
  return { state: currentState }
}

// 获取混合组检查的组索引
export function getMixedGroups(currentGroupIndex: number): number[] {
  // 判断当前组的形式 (1-based index)
  const groupNumber = currentGroupIndex + 1
  const remainder = groupNumber % 3
  const remainder6 = groupNumber % 6

  // 6N形式：混合当前组和前五组
  if (remainder6 === 0) {
    return [
      currentGroupIndex - 5,
      currentGroupIndex - 4,
      currentGroupIndex - 3,
      currentGroupIndex - 2,
      currentGroupIndex - 1,
      currentGroupIndex,
    ]
  }

  // 3N+2形式：混合当前组和前一组
  if (remainder === 2) {
    return [currentGroupIndex - 1, currentGroupIndex]
  }

  // 3N形式：混合当前组和前两组
  if (remainder === 0) {
    return [currentGroupIndex - 2, currentGroupIndex - 1, currentGroupIndex]
  }

  // 其他情况（通常不会发生）
  return [currentGroupIndex]
}

// 导航到指定状态
export function navigateToState(state: LearningState, groupIndex?: number, mixedGroups?: number[]): void {
  const unitStudyWordsStore = useUnitStudyWordsStore()

  // 如果提供了组索引，更新当前组
  if (groupIndex !== undefined) {
    unitStudyWordsStore.setCurrentGroupIndex(groupIndex)
  }

  // 如果提供了混合组，更新混合组
  if (mixedGroups) {
    unitStudyWordsStore.setMixedGroups(mixedGroups)
  }

  // 根据状态导航到相应页面
  switch (state) {
    case LearningState.WORD_MEMORY:
      uni.redirectTo({
        url: `/pages/wordStudy/wordMemory`,
      })
      break
    case LearningState.CUTTING:
      uni.redirectTo({
        url: `/pages/wordStudy/wordCutting`,
      })
      break
    case LearningState.MIXED_GROUP:
      uni.redirectTo({
        url: `/pages/wordStudy/mixedGroup`,
      })
      break
    case LearningState.MIXED_GROUP_6N:
      uni.redirectTo({
        url: `/pages/wordStudy/mixedGroup`,
      })
      break
    case LearningState.MIXED_GROUP_ALL:
      uni.redirectTo({
        url: `/pages/wordStudy/mixedGroupAll`,
      })
      break
    case LearningState.AFTER_CHECK:
      uni.redirectTo({
        url: `/pages/wordStudy/afterCheck`,
      })
      break
    case LearningState.COMPLETED:
      uni.redirectTo({
        url: `/pages/wordStudy/completed`,
      })
      break
  }
}

// 处理下一步操作
export async function handleNextStep(currentState: LearningState) {
  const unitStudyWordsStore = useUnitStudyWordsStore()

  const params: StudentWordShorthandStudyParams = {
    ...unitStudyWordsStore.commonRequestParams,
    lessonId: studentInfoStore.lessonId,
    endTime: formatDate(new Date()),
    duration: calculateDurationInSeconds(unitStudyWordsStore.commonRequestParams.startTime, formatDate(new Date())),
    words: unitStudyWordsStore.studyWords,
  }

  const isReviewEntry = unitStudyWordsStore.isReviewEntry

  const [error, result] = isReviewEntry
    ? await studentApi.reviewStudy(params)
    : await studentApi.shorthandStudy(params)

  if (error) {
    return handleApiError(error)
  }

  console.log(result)

  const currentGroupIndex = unitStudyWordsStore.currentGroupIndex
  const totalGroups = unitStudyWordsStore.totalGroups

  // 获取下一个状态
  const nextStateInfo = getNextState(currentState, currentGroupIndex, totalGroups)

  // 导航到下一个状态
  navigateToState(nextStateInfo.state, nextStateInfo.groupIndex, nextStateInfo.mixedGroups)
}
